/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.demo.richtext.adapter;

import com.demo.richtext.ResourceTable;
import com.demo.richtext.bean.TopicModel;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;

import java.util.List;

/**
 * @author TS
 */
public class TopicListProvider extends BaseItemProvider {
    private List<TopicModel> list;
    private AbilitySlice slice;

    public TopicListProvider(List<TopicModel> list, AbilitySlice slice) {
        this.list = list;
        this.slice = slice;
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        if (list != null && position >= 0 && position < list.size()) {
            return list.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component component,
                                  ComponentContainer componentContainer) {
        ViewHolder holder = null;
        if (component == null) {
            component = LayoutScatter.getInstance(slice)
                    .parse(ResourceTable.Layout_user_list_item, null, false);
            holder = new ViewHolder();
            holder.name = (Text) component.findComponentById(ResourceTable.Id_user_item);
            component.setTag(holder);
        } else {
            holder = (ViewHolder) component.getTag();
        }
        holder.name.setText(list.get(position).getTopic_Name());
        return component;
    }

    static class ViewHolder {
        private Text name;
    }
}
